﻿@model SMECustomerWebsite.Models.ViewModels.DaoManager.ChangeDaoViewModel

@if (Model.CurrentUser != null && Request.Cookies[Model.CurrentUser.UserName + "CHDError"] != null)
{
    <div class="alert alert-danger alert-dismissible fade in" role="alert">
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">×</span>
        </button>
        @Request.Cookies[Model.CurrentUser.UserName + "CHDError"].Value
    </div>
}
<div class="col-md-12 col-sm-12 col-xs-12">
    <div class="x_panel">
        <div class="x_title">
            <h2><i class="fa fa-bars"></i> @SMECustomerWebsite.Core.Resources.Resource.Option 1 <small>@SMECustomerWebsite.Core.Resources.Resource.AddnewByInput</small></h2>
            <ul class="nav navbar-right panel_toolbox">
                <li>
                    <a class="collapse-link"><i class="fa fa-chevron-up"></i></a>
                </li>
            </ul>
            <div class="clearfix"></div>
        </div>
        <div class="x_content">
            @Html.Partial("AddChangeDaoRequestMultipleByInput")
        </div>
    </div>
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
    <div class="x_panel">
        <div class="x_title">
            <h2><i class="fa fa-bars"></i> @SMECustomerWebsite.Core.Resources.Resource.Option 2 <small>@SMECustomerWebsite.Core.Resources.Resource.AddnewByExcel</small></h2>
            <ul class="nav navbar-right panel_toolbox">
                <li>
                    <a class="collapse-link"><i class="fa fa-chevron-up"></i></a>
                </li>
            </ul>
            <div class="clearfix"></div>
        </div>
        <div class="x_content">
            @Html.Partial("AddChangeDaoRequestByExcel")

        </div>
    </div>
</div>
@section scripts
{
    <script type="text/javascript">
        $(document).ready(function () {
            eraseCookie('@Model.CurrentUser.UserName' + 'CHDError');
            $.ajax({
                url: '/MSBO/ListMSBONameByBranch',
                type: "POST",
                data: { data: 1 },
                success: function (data_response) {
                    $('#oldDao').select2({
                        placeholder: "Select element",
                        data: data_response,
                    });
                    $('#newDao').select2({
                        placeholder: "Select element",
                        data: data_response,
                    });
                }
            });
        })
        $("#reason_dropdown").select2({
            placeholder: "Select reason",
            data: [{ id: '2', text: 'Do phân bổ lại cán bộ quản lý khách hàng' }, { id: '3', text: 'Do CBBH nghỉ việc/buộc thôi việc/điều chuyển sang bộ phận không thực hiện công tác bán hàng' }, { id: '4', text: 'Do CBBH nghỉ thai sản' }, { id: '5', text: 'Hoàn trả lại Khách hàng cán bộ quản lý do gán nhờ mã DAO' }, { id: '6', text: 'Chuyển giao khách hàng giữa MBD/MBE và Farmer; KMBO/SBO và PMBO' }, { id: '7', text: 'Lý do khác' }]
        });
        $("#custCif").select2({
            ajax: {
                url: "@Url.Action("GetListAllCustomer", "CustomerManager")",
                dataType: 'json',
                type: "POST",
                delay: 250,
                data: function (params) {
                    return {
                        searchText: params.term, // search term
                        page: params.page
                    };
                },
                processResults: function (data, params) {
                    params.page = params.page || 1;
                    return {
                        results: data,
                        pagination: {
                        }
                    };
                },
                cache: true
            },
            placeholder: "Search By CIF",
            allowClear: true,
            escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
            minimumInputLength: 1,
            templateResult: formatRepo, // omitted for brevity, see the source of this page
            templateSelection: formatRepoSelection // omitted for brevity, see the source of this page,
        });

        $("#custCif").val(null).trigger("change");
        function formatRepo(repo) {
            if (repo.loading) return repo.text;
            var markup = "<div class='select2-result-repository clearfix'>" +
              "<div class='select2-result-repository__meta'>" +
                "<div class='select2-result-repository__title'>" + repo.id + "</div>";
            markup += "<div class='select2-result-repository__description'>" + repo.custName + "</div>";
            markup += "<div class='select2-result-repository__statistics'>" +
              "<div class='select2-result-repository__forks'><i class='fa fa-flash'></i> " + repo.legalId + "</div>" +
            "</div>" +
            "</div></div>";

            return markup;
        }
        var initSelection = function (elem, cb) {
            console.log(elem)
            return elem
        }
        function formatRepoSelection(repo) {
            return repo.text;
        }

        function in_array(array, id) {
            for (var i = 0; i < array.length; i++) {
                return (array[i][0].length == id.length) && array[i][0].every(function (element, index) {
                    if (index < 2) {
                        return element == id[index];
                    } else {
                        return true;
                    }
                });
            }
            return false;
        }
        function pushIfExists(array, id, value) {
            for (var i = 0; i < array.length; i++) {
                if ((array[i][0].length == id.length) && array[i][0].every(function (element, index) {
                    if (index < 2) {
                        return element === id[index];
                } else {
                        return true;
                }
                })) {
                    array[i].push(value);
                }
            }
            return array;
        }
        var listRequest = [];
        function add_cif_request_to_list() {
            //alert("ok");
            var cif = $('#custCif').val();
            var newDao = $('#newDao').val();
            var listCifRequest = [];
            if (cif != null && newDao != null) {
                for (var i = 0; i < cif.length; i++) {
                    var is_in_array = false;
                    var cifRequest = [];
                    cifRequest.push(cif[i]);
                    cifRequest.push(newDao);
                    cifRequest.push(true);
                    //listCifRequest.push(cifRequest);
                    for (var j = 0; j < listRequest.length; j++) {
                        if ((listRequest[j][0].length == cifRequest.length) && listRequest[j][0].every(function (element, index) {
                            if (index < 2) {
                                return element === cifRequest[index];
                        } else {
                                return true;
                        }
                        })) {
                            is_in_array = true;
                        }
                    }

                    if (is_in_array === true) {
                        alert("Tồn tại Cif và DAO mới đã được thêm, rà soát và chọn lại");
                        break;
                    } else {
                        var itemRequest = [];
                        itemRequest.push(cifRequest);
                        listRequest.push(itemRequest);
                        continue;
                    }
                }
                if (is_in_array === false) {
                    createTableChangeDaoDetail();
                }
            } else {
                alert("choose Cif");
            }

            return false;
        }
        function createTableChangeDaoDetail() {
            var jsonData = JSON.stringify(listRequest);
            tableDetailRequest = $('#change_dao_request_detail_tb').DataTable({
                destroy: true,
                "bServerSide": true,
                "bProcessing": true,
                "responsive": true,
                "bAutoWidth": false,
                "aLengthMenu": [10, 30, 50, 100],
                "pageLength": 10,
                bFilter: false,
                bInfo: false,
                bPaginate: false,
                "sAjaxSource": '@Url.Action("GetChangeDaoInfo", "DaoManager")' + '?data=' + jsonData,
                "fnServerData": function (sSource, aoData, fnCallback) {
                    $.ajax({
                        "dataType": 'json',
                        "type": "POST",
                        "url": sSource,
                        "data": aoData,
                        "success": fnCallback
                    });
                },
                "createdRow": function (row, data, index) {
                    if (data[8] == true) {
                        $(row).addClass('disable');
                    } else {
                        if (data[9].IsSameSegment == false) {
                            $(row).addClass('change_dao_warning');
                        }
                        if (data[9].IsLast6MonthUpdate == true) {
                            $(row).addClass('change_dao_alert');
                        }
                    }

                    var listProduct = [];
                    for (i = 0; i < data[6].length; i++) {
                        var row = [];
                        name = data[1] + data[0] + data[6][i].NoProduct;
                        row.push(name);
                        row.push(data[6][i].NeedApprove);
                        row.push(data[6][i].NoProduct);
                        listProduct.push(row);
                    };
                    var currentCif = [];
                    currentCif.push(data[1]);
                    currentCif.push(data[0]);
                    currentCif.push(true);

                    var cif = $('#custCif').val();
                    var newDao = $('#newDao').val();
                    for (var i = 0; i < cif.length; i++) {
                        var cifRequest = [];
                        cifRequest.push(cif[i]);
                        cifRequest.push(newDao);
                        cifRequest.push(true);
                        if ((currentCif.length == cifRequest.length) && currentCif.every(function (element, index) { return element === cifRequest[index]; })) {
                            listRequest = pushIfExists(listRequest, currentCif, listProduct)
                            if (data[9].NeedApprove == false) {
                                listRequest[i][0][2] = false;
                            }
                        }
                    }
                },
                "sPaginationType": "simple_numbers",//"full_numbers",
                "aoColumns": [
                    { "sName": "CIF", "bSortable": false },
                    { "sName": "CIF", "bSortable": false },
                            { "sName": "USERNAME", "bSortable": false },
                            { "sName": "USERNAME", "bSortable": false },
                            { "sName": "USERNAME", "bSortable": false },
                            { "sName": "STATUS", "bSortable": false },
                            { "sName": "INFO", "className": 'column-title details-control', "bSortable": false }],
                "aoColumnDefs": [{
                    "sClass": "a-center ",
                    "aTargets": 0,
                    "mRender": function (data, type, full) {
                        if (full[9].NeedApprove == true) {
                            if (full[7] == false) {
                                return '<input type="checkbox" class="flat"  onchange="changeCif(\'' + full[1] + '\',\'' + full[0] + '\',this)"  id="chkbox_ccif_' + full[1] + full[0] + '" name="' + full[1] + full[0] + '">';
                            } else {
                                return '<input type="checkbox" class="flat" onchange="changeCif(\'' + full[1] + '\',\'' + full[0] + '\',this)"  id="chkbox_ccif_' + full[1] + full[0] + '" name="' + full[1] + full[0] + '" checked>';
                            }
                        } else {
                            return '';
                        }
                    }
                }, {
                    "sClass": "column-title",
                    "aTargets": [6],
                    "mRender": function (data, type, full) {
                        var text_return = ''
                        if (data.length == 0) {
                            text_return = 'Customer don\' t have any product in your branch';
                        } else {
                            text_return = '<a class=\"btn btn-primary btn-xs show_detail_row\" \"><i class="fa fa-plus-square"></i></a>';
                        }
                        text_return += '<a class=\"btn btn-danger btn-xs\" \" onclick="deleteChangeDaoCif(\'' + full[1] + '\',\'' + full[0] + '\');"><i class="fa fa-times"></i></a>';
                        return text_return
                    }
                }],
                "drawCallback": function (settings) {
                    $('table.custom_table th').removeClass().addClass('column-title');
                }
            });

        }
        function deleteChangeDaoCif(cif, newDao) {

            var checkCifDao = [];
            checkCifDao.push(cif);
            checkCifDao.push(newDao);
            checkCifDao.push(true);
            for (var i = 0; i < listRequest.length; i++) {
                if ((listRequest[i][0].length == checkCifDao.length) && listRequest[i][0].every(function (element, index) {
                    if (index < 2) {
                        return element === checkCifDao[index];
                } else {
                    return true;
                }
                })) {
                    listRequest.splice(i, 1);
                }
            }
            createTableChangeDaoDetail();
        }

        function changeCif(cif, newDao, dis) {
            var checkCifDao = [];
            checkCifDao.push(cif);
            checkCifDao.push(newDao);
            checkCifDao.push(true);
            for (var i = 0; i < listRequest.length; i++) {
                if ((listRequest[i][0].length == checkCifDao.length) && listRequest[i][0].every(function (element, index) {
                    if (index < 2) {
                        return element === checkCifDao[index];
                } else {
                    return true;
                }
                })) {
                    listRequest[i][0][2] = dis.checked;
                }
            }
        }

        function change(dis) {
            for (i = 0; i < listRequest.length; i++) {
                if (listRequest[i].length > 1) {
                    listProduct = listRequest[i][1];
                    for (j = 0; j < listProduct.length; j++) {
                        if (listProduct[j][0] == dis.name) {
                            listProduct[j][1] = dis.checked;
                        }
                    }
                }
            }
        }
        $('#change_dao_request_detail_tb').on('click', 'td.details-control .show_detail_row', function () {
            var tr = $(this).closest('tr');
            var row = tableDetailRequest.row(tr);

            if (row.child.isShown()) {
                // This row is already open - close it
                row.child(format(row.data())).hide();
                tr.removeClass('shown');
                $('tr td a.show_detail_row i').addClass('fa-plus-square');
                $('tr td a.show_detail_row i').removeClass('fa-minus-square');
            }
            else {
                // Open this row
                var dataRow = row.data();
                var detail = row.child(format(row.data())).show();
                tr.addClass('shown');
                $('tr.shown td a.show_detail_row i').removeClass('fa-plus-square');
                $('tr.shown td a.show_detail_row i').addClass('fa-minus-square');
            }
        });

        function format(d) {
            var position = 6;
            // `d` is the original data object for the row
            var html = '<table class="table table-child table_overdue custom_table table-bordered table-striped jambo_table"  cellpadding="5" cellspacing="0" border="0"><th class="column-title">Check</th><th class="column-title">TYPE</th><th class="column-title">NO.</th><th class="column-title">Old DAO</th><th class="column-title">DATA DATE</th>';
            if (d[position].length == 0) {
                html = html +
                    '<tr>' +
                    '<td colspan="' + position + '">NO DATA</td>' +
                    '</tr>';
            }
            var isCheck;
            var classDisable;
            var idProduct;
            for (var i = 0; i < d[position].length; i++) {
                if (d[position][i].NeedApprove == true) {
                    if (d[position][i].IsApproved == false) {
                        isCheck = '<input type="checkbox" class="flat chkbox_cdproduct" onchange="change(this)" id="chkbox_cdproduct_' + idProduct + '" name="' + d[1] + d[0] + d[position][i].NoProduct + '">';
                    } else {
                        isCheck = '<input type="checkbox" class="flat chkbox_cdproduct" onchange="change(this)" id="chkbox_cdproduct_' + idProduct + '" name="' + d[1] + d[0] + d[position][i].NoProduct + '" checked>';
                    }
                } else {
                    isCheck = '';
                }
                html = html +
                    '<tr>' +
                    '<td>' + isCheck + '</td>' +
                    '<td>' + d[position][i].TypeProduct + '</td>' +
                     '<td>' + d[position][i].NoProduct + '</td>' +
                     '<td>' + d[position][i].Dao + '</td>' +
                     '<td>' + d[position][i].DataDate + '</td>' +
                     '</tr>';
            }
            html = html + '</table>';
            return html;
        }

        function submitData() {
            if (confirm('Are you sure?')) {
                var jsonData = JSON.stringify(listRequest);
                var reason = $('#reason_dropdown').val();
                var reasonDescription = $('#reason_description_txt').val();
                var isDeviation = false;
                if ($('#chkbox_is_deviation')[0] != undefined) {
                    isDeviation = $('#chkbox_is_deviation')[0].checked;
                }

                $.ajax({
                    url: '@Url.Action("UpdateChangeDaoCifMultiple", "DaoManager")',
                    type: "POST",
                    data: { dataCif: jsonData, dataProduct: jsonData, reason: reason, reasonDescription: reasonDescription, check: isDeviation },
                    success: function (data_response) {
                        if (data_response != '') {
                            if (data_response.MessageType == 0) {
                                createCookie('@Model.CurrentUser.UserName' + 'CHDSuccess', data_response.Message, 1);

                                window.location.href = '@Url.Action("ListChangeDaoRequest", "DaoManager")';
                            } else {
                                createCookie('@Model.CurrentUser.UserName' + 'CHDError', data_response.Message, 1);
                                location.reload();
                            }
                        }
                    }
                })
            } else {
            }
            return false;
        }
    </script>
}